import G6 from '@antv/g6'

G6.registerEdge('smooth', {
  draw (cfg, group) {

    // const { sourceNode, targetNode, startPoint, endPoint } = cfg
    // const sourceNodeBBox = sourceNode.getBBox();
    // const targetNodeBBox = targetNode.getBBox();
    // const dir = targetNodeBBox.x > sourceNodeBBox.centerX ? 'right' : 'left'

    // const startPointX = dir === 'right' ? // 根据左右方向决定起止点位置
    //   sourceNodeBBox.centerX + sourceNodeBBox.width / 2 :
    //   sourceNodeBBox.centerX - sourceNodeBBox.width / 2
    // const targetPointX = dir === 'right' ?
    //   targetNodeBBox.centerX - targetNodeBBox.width / 2 :
    //   targetNodeBBox.centerX + targetNodeBBox.width / 2
    // const halfX = (startPointX + targetPointX) / 2


    // const path = [
    //   ['M', startPointX, sourceNodeBBox.centerY],
    //   ['L', halfX, sourceNodeBBox.centerY],
    //   ['L', halfX, targetNodeBBox.centerY],
    //   ['L', targetPointX, targetNodeBBox.centerY]
    // ]

    const startPoint = cfg.startPoint;
    const endPoint = cfg.endPoint;

    const Ydiff = endPoint.y - startPoint.y;

    const slope = Ydiff !== 0 ? Math.min(500 / Math.abs(Ydiff), 20) : 0;

    const cpOffset = slope > 15 ? 0 : 16;
    const offset = Ydiff < 0 ? cpOffset : -cpOffset;

    const line1EndPoint = {
      x: startPoint.x + slope,
      y: endPoint.y + offset,
    };
    const line2StartPoint = {
      x: line1EndPoint.x + cpOffset,
      y: endPoint.y,
    };

    // 控制点坐标
    const controlPoint = {
      x:
        ((line1EndPoint.x - startPoint.x) * (endPoint.y - startPoint.y)) /
          (line1EndPoint.y - startPoint.y) +
        startPoint.x,
      y: endPoint.y,
    };

    let path = [
      ['M', startPoint.x, startPoint.y],
      ['L', line1EndPoint.x, line1EndPoint.y],
      ['Q', controlPoint.x, controlPoint.y, line2StartPoint.x, line2StartPoint.y],
      ['L', endPoint.x, endPoint.y],
    ];

    if (Math.abs(Ydiff) <= 5) {
      path = [
        ['M', startPoint.x, startPoint.y],
        ['L', endPoint.x, endPoint.y],
      ];
    }

    const shape = group.addShape('path', {
      attrs: {
        stroke: '#aab7c4',
        path
      },
      name: 'smooth-path-shape'
    })

    return shape
  }
})